package com.ysd.lis.controller.sys;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.json.XML;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ysd.common.Result;
import com.ysd.lis.controller.pub.BaseController;
import com.ysd.lis.dto.InterfaceDto;
import com.ysd.lis.entity.SysInterfaceMethExtParam;
import com.ysd.lis.entity.SysInterfaceMethod;
import com.ysd.lis.entity.SysInterfaceMethodOutparam;
import com.ysd.lis.request.InterfaceParam;
import com.ysd.lis.service.SysInterfaceMethExtParamService;
import com.ysd.lis.service.SysInterfaceMethodOutparamService;
import com.ysd.lis.service.SysInterfaceMethodService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 员工表
 * 前端控制器
 * </p>
 *
 * @author prs
 * @since 2024-04-25
 */
@Api(tags = "接口方法管理")
@RestController
@RequestMapping("/api/sys/sysInterfaceMethod")
public class SysInterfaceMethodController extends BaseController {

    @Autowired
    SysInterfaceMethodService sysInterfaceMethodService;
    @Autowired
    SysInterfaceMethExtParamService sysInterfaceMethExtParamService;
    @Autowired
    SysInterfaceMethodOutparamService sysInterfaceMethodOutparamService;


    @ApiOperation("查询")
    @GetMapping("/findInterfaceMethodList")
    public Result findInterfaceMethodList(InterfaceParam param) {
        return sysInterfaceMethodService.findInterfaceMethodList(param);
    }

    @ApiOperation("修改")
    @PostMapping("/saveOrUpdateInterfaceMethod")
    public Result saveOrUpdateInterfaceMethod(@RequestBody InterfaceDto dto) {
        return sysInterfaceMethodService.saveOrUpdateInterfaceMethod(dto);
    }

    @ApiOperation("双击新增接口")
    @PostMapping("/saveInterfaceMethod")
    public Result saveInterfaceMethod(@RequestBody SysInterfaceMethod sysInterfaceMethod) {
        boolean save = sysInterfaceMethodService.save(sysInterfaceMethod);
        if (save) {
            return Result.succ(1, "成功", sysInterfaceMethod);
        } else {
            return Result.fail(400, "失败", "");
        }
    }


    @ApiOperation("批量删除")
    @PostMapping("/deleteBatchInterfaceMethod")
    public Result deleteBatchInterfaceMethod(@RequestBody InterfaceDto dto) {
        return sysInterfaceMethodService.deleteBatchInterfaceMethod(dto);
    }

    @ApiOperation("上传接口JSON模板")
    @PostMapping("/uploadJsonInterfaceMethodParam")
    public Result uploadJsonInterfaceMethodParam(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();

        String interfaceMethodId = request.getParameter("interfaceMethodId");
        String interfaceId = request.getParameter("interfaceId");

        InputStream inputStream = file.getInputStream();
        StringBuffer sb = new StringBuffer();
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail(400, "上传的json格式有误，请核实后上传", "");
        }


        JSONObject jsonObject = new JSONObject();

        if (StrUtil.isNotEmpty(sb.toString()) && sb.toString().startsWith("{")) {
            jsonObject = JSONUtil.parseObj(sb);
        } else {
            jsonObject = XML.toJSONObject(sb.toString());
        }


        SysInterfaceMethod sysInterfaceMethod = new SysInterfaceMethod();
        sysInterfaceMethod.setReqParam(JSONUtil.toJsonStr(jsonObject));
        sysInterfaceMethod.setId(interfaceMethodId);
        sysInterfaceMethodService.updateById(sysInterfaceMethod);


        //解析json报文
        ObjectMapper mapper = new ObjectMapper();
        try {
            List<String> list = new ArrayList<>();
            JsonNode rootNode = mapper.readTree(jsonObject.toString());
            List<String> list1 = traverseJsonNode(rootNode, "", list);

            list1 = list1.stream().distinct().collect(Collectors.toList());

            List<SysInterfaceMethExtParam> dataList = new ArrayList<>();
            Set<String> set = new HashSet<>();
            Set<String> set2 = new HashSet<>();
            for (int i = 0; i < list1.size(); i++) {
                System.out.println(list1.get(i));
                String[] split = list1.get(i).split("@@");//截取所有的报文
                for (int j = 0; j < split.length; j++) {
                    SysInterfaceMethExtParam sysInterfaceMethExtParam = new SysInterfaceMethExtParam();
                    if (j == 0) {
                        if (set.add(split[j])) {
                            sysInterfaceMethExtParam.setParamId(UUID.randomUUID() + "");
                            sysInterfaceMethExtParam.setExtCode(split[j]);
                            sysInterfaceMethExtParam.setInterfaceMethodId(interfaceMethodId);
                            sysInterfaceMethExtParam.setInterfaceId(interfaceId);
                            if (list1.get(i).indexOf("@@") > -1) {
                                sysInterfaceMethExtParam.setJsonPath(list1.get(i).substring(0, list1.get(i).indexOf("@@")));
                            } else {
                                sysInterfaceMethExtParam.setJsonPath(list1.get(i));
                            }
                            sysInterfaceMethExtParam.setType(1);
                            sysInterfaceMethExtParam.setSymbol("equal");
                            dataList.add(sysInterfaceMethExtParam);
                        }
                    } else if (j < split.length - 1) {
                        if (set2.add(split[j])) {
                            sysInterfaceMethExtParam.setParamId(UUID.randomUUID() + "");
                            int finalJ = j;
                            SysInterfaceMethExtParam sysInterfaceMethExtParam1 = dataList.stream().filter(a -> a.getExtCode().equals(split[finalJ - 1])).findFirst().get();
                            sysInterfaceMethExtParam.setParamParentId(sysInterfaceMethExtParam1.getParamId());
                            sysInterfaceMethExtParam.setExtCode(split[j]);
                            sysInterfaceMethExtParam.setInterfaceMethodId(interfaceMethodId);
                            sysInterfaceMethExtParam.setInterfaceId(interfaceId);
                            sysInterfaceMethExtParam.setJsonPath(list1.get(i).substring(0, list1.get(i).lastIndexOf("@@")));
                            sysInterfaceMethExtParam.setType(1);
                            sysInterfaceMethExtParam.setSymbol("equal");
                            dataList.add(sysInterfaceMethExtParam);
                        }
                    } else {
                        int finalJ = j;
                        SysInterfaceMethExtParam sysInterfaceMethExtParam1 = dataList.stream().filter(a -> a.getExtCode().equals(split[finalJ - 1])).findFirst().get();
                        sysInterfaceMethExtParam.setParamId(UUID.randomUUID().toString());
                        sysInterfaceMethExtParam.setParamParentId(sysInterfaceMethExtParam1.getParamId());
                        sysInterfaceMethExtParam.setExtCode(split[j]);
                        sysInterfaceMethExtParam.setInterfaceMethodId(interfaceMethodId);
                        sysInterfaceMethExtParam.setInterfaceId(interfaceId);
                        sysInterfaceMethExtParam.setJsonPath(list1.get(i));
                        sysInterfaceMethExtParam.setType(1);
                        sysInterfaceMethExtParam.setSymbol("equal");
                        dataList.add(sysInterfaceMethExtParam);
                    }

                }
            }

            System.out.println(JSONUtil.toJsonStr(dataList));
            //删除掉之前的数据，重插
            LambdaQueryWrapper<SysInterfaceMethExtParam> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SysInterfaceMethExtParam::getInterfaceMethodId, interfaceMethodId)
                    .eq(SysInterfaceMethExtParam::getInterfaceId, interfaceId);
            sysInterfaceMethExtParamService.remove(lambdaQueryWrapper);
            sysInterfaceMethExtParamService.saveBatch(dataList);


        } catch (IOException e) {
            e.printStackTrace();
        }


        return Result.succ(1, "导入成功", "");
    }

    @ApiOperation("上传接口JSON出参模板")
    @PostMapping("/uploadJsonInterfaceMethodOutParam")
    public Result uploadJsonInterfaceMethodOutParam(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        String interfaceMethodId = request.getParameter("interfaceMethodId");
        String interfaceId = request.getParameter("interfaceId");
        InputStream inputStream = file.getInputStream();
        StringBuffer sb = new StringBuffer();
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail(400, "上传的json格式有误，请核实后上传", "");
        }

        JSONObject jsonObject = new JSONObject();
        if (StrUtil.isNotEmpty(sb.toString()) && sb.toString().startsWith("{")) {
            jsonObject = JSONUtil.parseObj(sb);
        } else {
            jsonObject = XML.toJSONObject(sb.toString());
        }

        SysInterfaceMethod sysInterfaceMethod = new SysInterfaceMethod();
        sysInterfaceMethod.setReqParam(JSONUtil.toJsonStr(jsonObject));
        sysInterfaceMethod.setId(interfaceMethodId);
        sysInterfaceMethodService.updateById(sysInterfaceMethod);

        //解析json报文
        ObjectMapper mapper = new ObjectMapper();
        try {
            List<String> list = new ArrayList<>();
            JsonNode rootNode = mapper.readTree(jsonObject.toString());
            List<String> list1 = traverseJsonNode(rootNode, "", list);

            list1 = list1.stream().distinct().collect(Collectors.toList());

            List<SysInterfaceMethodOutparam> dataList = new ArrayList<>();
            Set<String> set = new HashSet<>();
            Set<String> set2 = new HashSet<>();
            for (int i = 0; i < list1.size(); i++) {
                System.out.println(list1.get(i));
                String[] split = list1.get(i).split("@@");//截取所有的报文
                for (int j = 0; j < split.length; j++) {
                    SysInterfaceMethodOutparam sysInterfaceMethodOutparam = new SysInterfaceMethodOutparam();
                    if (j == 0) {
                        if (set.add(split[j])) {
                            sysInterfaceMethodOutparam.setParamId(UUID.randomUUID() + "");
                            sysInterfaceMethodOutparam.setOutCode(split[j]);
                            sysInterfaceMethodOutparam.setMethodId(interfaceMethodId);
                            sysInterfaceMethodOutparam.setInterfaceId(interfaceId);
                            if (list1.get(i).indexOf("@@") > -1) {
                                sysInterfaceMethodOutparam.setJsonPath(list1.get(i).substring(0, list1.get(i).indexOf("@@")));
                            } else {
                                sysInterfaceMethodOutparam.setJsonPath(list1.get(i));
                            }
                            sysInterfaceMethodOutparam.setState(true);
                            dataList.add(sysInterfaceMethodOutparam);
                        }
                    } else if (j < split.length - 1) {
                        if (set2.add(split[j])) {
                            int finalJ = j;
                            SysInterfaceMethodOutparam sysInterfaceMethodOutparam1 = dataList.stream().filter(a -> a.getOutCode().equals(split[finalJ - 1])).findFirst().get();
                            sysInterfaceMethodOutparam.setParamId(UUID.randomUUID() + "");
                            sysInterfaceMethodOutparam.setParamParentId(sysInterfaceMethodOutparam1.getParamId());
                            sysInterfaceMethodOutparam.setOutCode(split[j]);
                            sysInterfaceMethodOutparam.setMethodId(interfaceMethodId);
                            sysInterfaceMethodOutparam.setInterfaceId(interfaceId);
                            sysInterfaceMethodOutparam.setJsonPath(list1.get(i).substring(0, list1.get(i).lastIndexOf("@@")));
                            sysInterfaceMethodOutparam.setState(true);
                            dataList.add(sysInterfaceMethodOutparam);
                        }
                    } else {
                        int finalJ = j;
                        SysInterfaceMethodOutparam sysInterfaceMethodOutparam1 = dataList.stream().filter(a -> a.getOutCode().equals(split[finalJ - 1])).findFirst().get();
                        sysInterfaceMethodOutparam.setParamId(UUID.randomUUID().toString());
                        sysInterfaceMethodOutparam.setParamParentId(sysInterfaceMethodOutparam1.getParamId());
                        sysInterfaceMethodOutparam.setOutCode(split[j]);
                        sysInterfaceMethodOutparam.setMethodId(interfaceMethodId);
                        sysInterfaceMethodOutparam.setInterfaceId(interfaceId);
                        sysInterfaceMethodOutparam.setJsonPath(list1.get(i));
                        sysInterfaceMethodOutparam.setState(true);
                        dataList.add(sysInterfaceMethodOutparam);
                    }
                }
            }
            //删除掉之前的数据，重插
            LambdaQueryWrapper<SysInterfaceMethodOutparam> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SysInterfaceMethodOutparam::getMethodId, interfaceMethodId)
                    .eq(SysInterfaceMethodOutparam::getInterfaceId, interfaceId);
            sysInterfaceMethodOutparamService.remove(lambdaQueryWrapper);
            sysInterfaceMethodOutparamService.saveBatch(dataList);


        } catch (IOException e) {
            e.printStackTrace();
        }


        return Result.succ(1, "导入成功", "");
    }

    private static List<String> traverseJsonNode(JsonNode node, String prefix, List<String> list) {
        if (node.isObject()) {
            for (Iterator<String> it = node.fieldNames(); it.hasNext(); ) {
                String fieldName = it.next();
                String newPrefix = prefix.isEmpty() ? fieldName : prefix + "@@" + fieldName;
                traverseJsonNode(node.get(fieldName), newPrefix, list);
            }
        } else if (node.isArray()) {
            for (JsonNode arrayNode : node) {
                String newPrefix = prefix;
                traverseJsonNode(arrayNode, newPrefix, list);
            }
        } else {
            list.add(prefix);
        }
        return list;
    }

}
